package com.qiangesoft.district.gaode;

import com.qiangesoft.district.entity.SysArea;
import com.qiangesoft.district.gaode.constant.RegionLevelEnum;
import com.qiangesoft.district.gaode.model.District;
import com.qiangesoft.district.gaode.model.DistrictConstant;
import com.qiangesoft.district.gaode.model.GaoDeDistrictResult;
import com.qiangesoft.district.service.ISysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域数据
 *
 * @author qiangesoft
 * @date 2023-07-18
 */
@Slf4j
@Component
public class AreaTask {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ISysAreaService sysAreaService;

    /**
     * 每天10点执行一次
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void pullArea() {
        log.info("Update area data begin==================>");
        long startTime = System.currentTimeMillis();

        StringBuilder sendUrl = new StringBuilder(DistrictConstant.DISTRICT_URL)
                .append("?key=").append(GaoDeApi.KEY_VALUE)
                .append("&keywords=").append(DistrictConstant.ZQ_KEYWORD_VALUE)
                .append("&subdistrict=4&extensions=base");
        ResponseEntity<GaoDeDistrictResult> responseEntity = restTemplate.getForEntity(sendUrl.toString(), GaoDeDistrictResult.class);
        // 请求异常，可能由于网络等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Gaode interface error");
            return;
        }

        // 请求失败
        GaoDeDistrictResult gaoDeDistrictResult = responseEntity.getBody();
        String status = gaoDeDistrictResult.getStatus();
        if (!status.equals(GaoDeApi.SUCCESS)) {
            log.info("Request for Gaode interface failed");
            return;
        }

        // 请求无数据
        List<District> districts = gaoDeDistrictResult.getDistricts();
        if (CollectionUtils.isEmpty(districts)) {
            log.info("Request for Gaode interface no data");
            return;
        }

        // 保存数据
        this.saveData(districts, null);

        long endTime = System.currentTimeMillis();
        log.info("spend time:" + (endTime - startTime));
        log.info("Update area data end<==================");
    }

    /**
     * 保存数据
     *
     * @param districts
     * @param parentId
     */
    private void saveData(List<District> districts, Long parentId) {
        if (CollectionUtils.isEmpty(districts)) {
            return;
        }

        // 排序
        districts.sort(Comparator.comparing(District::getAdcode));
        // 国家一级特殊处理
        if (parentId == null) {
            districts = districts.stream().filter(e -> RegionLevelEnum.COUNTRY.getCode().equals(e.getLevel())).collect(Collectors.toList());
        }

        // 执行保存
        List<SysArea> areaList = new ArrayList<>();
        for (District district : districts) {
            SysArea sysArea = new SysArea();
            sysArea.setCode(district.getAdcode());
            sysArea.setAreaCode(district.getCitycode().toString());
            sysArea.setName(district.getName());
            sysArea.setFullName(district.getName());
            sysArea.setSortValue(1);
            String center2 = district.getCenter();
            if (StringUtils.isNotBlank(center2)) {
                String[] split = center2.split(",");
                sysArea.setLongitude(split[0]);
                sysArea.setLatitude(split[1]);
            }
            String level = RegionLevelEnum.getCodeByDes(district.getLevel());
            sysArea.setLevel(level);
            sysArea.setDelFlag(false);
            sysArea.setParentId(parentId);
            areaList.add(sysArea);
        }
        sysAreaService.saveBatch(areaList);

        // 下级
        for (int i = 0; i < districts.size(); i++) {
            District district = districts.get(i);
            List<District> children = district.getDistricts();
            if (!CollectionUtils.isEmpty(children)) {
                this.saveData(children, areaList.get(i).getId());
            }
        }
    }

}